import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import yaml from 'js-yaml';
import { execSync }  from 'child_process';
import { fileURLToPath } from 'url';

// 获取当前文件路径
const __filename = fileURLToPath(import.meta.url);
// 获取当前文件所在目录
const __dirname = path.dirname(__filename);

// 配置项
const config = {
  version: '0.0.0', // 从package.json获取
  releaseDir: '',
};

// 读取版本号
const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
config.version = packageJson.version;
config.releaseDir = path.join(__dirname, 'release', config.version);

// 生成SHA512哈希
function generateSha512(filePath) {
  const fileBuffer = fs.readFileSync(filePath);
  const hashSum = crypto.createHash('sha512');
  hashSum.update(fileBuffer);
  return hashSum.digest('base64');
}

// 创建latest.yml文件
function createLatestYml(platform, filePath, fileName) {
  const fileSize = fs.statSync(filePath).size;
  const sha512 = generateSha512(filePath);
  
  const ymlData = {
    version: config.version,
    files: [
      {
        url: fileName,
        sha512: sha512,
        size: fileSize
      }
    ],
    path: fileName,
    sha512: sha512,
    releaseDate: new Date().toISOString()
  };
  
  const ymlFileName = platform === 'win' ? 'latest.yml' : `latest-${platform}.yml`;
  const ymlPath = path.join(config.releaseDir, ymlFileName);
  fs.writeFileSync(ymlPath, yaml.dump(ymlData), 'utf8');
  
  console.log(`Created ${ymlFileName} with hash: ${sha512}`);
  return { ymlPath, ymlFileName };
}

// 上传文件到服务器

// 主函数
async function main() {
  // 处理Windows安装包
  const winInstallerName = `Bool Servey-Windows-${config.version}-Setup.exe`;
  const winInstallerPath = path.join(config.releaseDir, winInstallerName);
  
  if (fs.existsSync(winInstallerPath)) {
    // 创建并上传latest.yml
    const { ymlPath, ymlFileName } = createLatestYml('win', winInstallerPath, winInstallerName);
    
  } else {
    console.log(`Windows installer not found at ${winInstallerPath}`);
  }
  
  // 处理macOS安装包
  const macInstallerName = `Bool Servey-Mac-${config.version}-Installer.dmg`;
  const macInstallerPath = path.join(config.releaseDir, macInstallerName);
  
  if (fs.existsSync(macInstallerPath)) {
    // 创建并上传latest-mac.yml
    const { ymlPath, ymlFileName } = createLatestYml('mac', macInstallerPath, macInstallerName);
    
  } else {
    console.log(`macOS installer not found at ${macInstallerPath}`);
  }
  
  console.log('Update deployment completed.');
}

main().catch(console.error);